package com.da.javatest.interview.other.print;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenlida
 * @date 2020/10/20 14:52
 * @description
 */
public class PrintABC1 {
    private int times;
    private int state;
    private Lock lock = new ReentrantLock();

    public PrintABC1(int times) {
        this.times = times;
    }

    private void print(String msg, int targetState) {
        for (int i = 0; i < times;) {
            lock.lock();
            if (state % 3 == targetState) {
                i++;
                state++;
                System.out.print(msg);
            }
            lock.unlock();
        }
    }

    public void printA() {
        print("A", 0);
    }

    public void printB() {
        print("B", 1);
    }

    public void printC() {
        print("C", 2);
    }

    public static void main(String[] args) {
        PrintABC1 printABC1 = new PrintABC1(10);
        new Thread(printABC1::printA).start();
        new Thread(printABC1::printB).start();
        new Thread(printABC1::printC).start();
    }
}
